package setting

import (
	"encoding/json"
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/core/response"
	"likeadmin/util"
)

const (
	StorageStatusOn  = 1 // 状态开启
	StorageStatusOff = 0 // 状态关闭
)

type ISettingStorageService interface {
	List() (list []resp.StorageSettingResp, e error)
	Detail(engine string) (res resp.StorageSettingResp, e error)
	Edit(editReq req.SettingStorageEditReq) (e error)
}

// NewSettingStorageService 初始化
func NewSettingStorageService(db *gorm.DB) ISettingStorageService {
	return &settingStorageService{db: db}
}

// settingStorageService 存储配置服务实现类
type settingStorageService struct {
	db *gorm.DB
}

var storageList = []map[string]interface{}{
	{"name": "本地存储", "alias": "local", "describe": "存储在本地服务器", "status": 0},
}

// List 存储列表
func (sSrv settingStorageService) List() (list []resp.StorageSettingResp, e error) {
	data, err := util.ConfigUtil.Get(sSrv.db, "storage")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}

	// 获取默认开启项
	defaultEngine, err := util.ConfigUtil.GetVal(sSrv.db, "storage", "default", "local")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}

	for _, name := range data {
		if name != "" {
			var item resp.StorageSettingResp
			err := json.Unmarshal([]byte(name), &item)
			// 排除 default 值
			if err != nil {
				println(err.Error())
				continue
			}

			if defaultEngine == item.Engine {
				item.Status = StorageStatusOn
			} else {
				item.Status = StorageStatusOff
			}

			list = append(list, item)
		}
	}

	return list, nil
}

// Detail 存储详情
func (sSrv settingStorageService) Detail(engine string) (res resp.StorageSettingResp, e error) {
	data, err := util.ConfigUtil.GetVal(sSrv.db, "storage", engine, "")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}

	// 获取默认开启项
	defaultEngine, err := util.ConfigUtil.GetVal(sSrv.db, "storage", "default", "local")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}

	var item resp.StorageSettingResp
	_ = json.Unmarshal([]byte(data), &item)

	if defaultEngine == item.Engine {
		item.Status = StorageStatusOn
	} else {
		item.Status = StorageStatusOff
	}

	response.Copy(&res, item)
	return
}

// Edit 存储编辑
func (sSrv settingStorageService) Edit(editReq req.SettingStorageEditReq) (e error) {

	// 设置开启
	if editReq.Status == StorageStatusOn {
		err := util.ConfigUtil.Set(sSrv.db, "storage", "default", editReq.Engine)
		if e = response.CheckErr(err, "Save Set name err"); e != nil {
			return
		}
	}

	editReq.Status = 0
	marshal, err := json.Marshal(editReq)
	if err != nil {
		if e = response.CheckErr(err, "Save Set name err"); e != nil {
			return
		}
	}

	err = util.ConfigUtil.Set(sSrv.db, "storage", editReq.Engine, string(marshal))
	if e = response.CheckErr(err, "Save Set name err"); e != nil {
		return
	}

	// 删除缓存
	util.RedisUtil.HDel("storage", "default")
	util.RedisUtil.HDel("storage", editReq.Engine)

	return
}
